package controllers

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"net/http"
	"time"
)

// 接口客户端请求的参数
type ClientRequest struct {
	UserName string `json:"user_name" binding:"required"`
	Password string `json:"password" binding:"required"`
	Remark   string `json:"remark"`
}

// 返回客户端的数据
type ClientResponse struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

// 登录操作
func Login(c *gin.Context) {
	var requestData ClientRequest
	var response ClientResponse
	err := c.Bind(&requestData) //执行绑定
	//fmt.Println("绑定的数据：", requestData)
	if err != nil {
		fmt.Println("错误信息：", err)
		response.Code = http.StatusBadRequest
		response.Msg = "请求参数错误"
		c.JSON(http.StatusBadRequest, response)
		return
	}
	if requestData.UserName == "zhangsan" && requestData.Password == "123456" {
		response.Code = http.StatusOK
		response.Msg = "登录成功"
		response.Data = "OK"
		c.JSON(http.StatusOK, response)
		return
	}
	c.JSON(http.StatusBadRequest, ClientResponse{
		Code: http.StatusBadRequest,
		Msg:  "登录失败",
		Data: nil,
	})
	return
}

// 请求三方服务登录
func ThirdLogin(c *gin.Context) {
	//调用第三方接口的请求数据
	type ThirdAPIRequest struct {
		LoginUserName string `json:"login_user_name"`
		LoginPassword string `json:"login_password"`
	}

	//调用第三方接口的返回结果
	type ThirdAPIResponse struct {
		Code int    `json:"res_code"`
		Msg  string `json:"res_message"`
		Data string `json:"res_data"`
	}

	var requestData ClientRequest
	err := c.Bind(&requestData) //执行绑定
	if err != nil {
		fmt.Println("错误信息：", err)
		c.JSON(http.StatusBadRequest, ClientResponse{
			Code: http.StatusBadRequest,
			Msg:  "参数错误",
		})
		return
	}

	//请求第三方API接口数据
	url := "http://localhost/t.php"
	requestThirdData := ThirdAPIRequest{
		LoginUserName: requestData.UserName,
		LoginPassword: requestData.Password,
	}
	data, err := requestAPI(url, requestThirdData, "application/json")
	var responseThirdData ThirdAPIResponse
	json.Unmarshal(data, &responseThirdData)
	fmt.Println("responseThirdData", responseThirdData)

	c.JSON(http.StatusOK, ClientResponse{
		Code: responseThirdData.Code,
		Msg:  responseThirdData.Msg,
		Data: responseThirdData.Data,
	})
	return
}

// 发送POST请求
// url：         请求地址
// data：        POST请求提交的数据
// contentType： 请求体格式，如：application/json
// content：     请求放回的内容
func requestAPI(url string, data interface{}, contentType string) ([]byte, error) {
	//创建调用API接口的client
	client := &http.Client{Timeout: 5 * time.Second}
	jsonStr, _ := json.Marshal(data)
	fmt.Println("请求三方接口信息：", url, bytes.NewBuffer(jsonStr))
	resp, err := client.Post(url, contentType, bytes.NewBuffer(jsonStr))
	if err != nil {
		fmt.Println("调用API接口出现了错误:", err)
		return nil, err
	}
	res, err := ioutil.ReadAll(resp.Body)
	fmt.Println("三方接口返回信息：", bytes.NewBuffer(res), err)
	return res, err

}

func Logout(c *gin.Context) {

}
